import { Component, OnInit } from '@angular/core';
import { ActivatedRoute, ParamMap, Router } from '@angular/router';

import { Observable } from 'rxjs';
import { switchMap } from 'rxjs/operators';

import { Crisis, CrisisService } from './crisis.service';

@Component({
  template: `
    <ul class="items">
      <li *ngFor="let crisis of crises$; trackBy: trackByCrisis | async">
        <a [routerLink]="[crisis.id]" [class.selected]="isSelected(crisis)">
          <span class="badge">{{crisis.id}}</span>
          {{crisis.name}}
        </a>
      </li>
    </ul>

    <router-outlet></router-outlet>
  `
})
export class CrisisListComponent implements OnInit {
  crises$: Observable<Crisis[]>;
  selectedId: number;

  constructor(
    private service: CrisisService,
    private route: ActivatedRoute,
    private router: Router
  ) { }

  ngOnInit(): void {
    this.crises$ = this.route.paramMap.pipe(switchMap((params: ParamMap) => {
      this.selectedId = +params.get('id');
      return this.service.getCrises();
    }))
  }

  trackByCrisis(index: number, crisis: Crisis): number {
    return crisis.id
  }

  isSelected(crisis: Crisis): boolean {
    return crisis.id === this.selectedId;
  }

  onSelect(crisis: Crisis): void {
    this.selectedId = crisis.id;

    // Navigate with relative link
    this.router.navigate([crisis.id], { relativeTo: this.route });
  }
}